package org.apm.data.check;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.client.Client;

import com.alibaba.fastjson.JSONObject;

public class JavaTraceDataReIndex extends DataReIndex {
    private static final Logger LOGGER = LogManager.getLogger(JavaTraceDataReIndex.class);
    private static final String TYPE = "JavaTraceData";

    public JavaTraceDataReIndex() {}

    public JavaTraceDataReIndex(Client client, BulkProcessor esBulkProcessor) {
        super(client, esBulkProcessor);
    }

    @Override
    protected boolean checkIndex(String index) {
        return index.contains(TYPE.toLowerCase());
    }

    @Override
    protected DataBean processData(String dataSource) {
        DataBean dataBean = new DataBean();
        try {
            JSONObject jsonObject = JSONObject.parseObject(dataSource);
            JSONObject defaultMsg = jsonObject.getJSONObject("DefaultMessage");
            String traceMsg = defaultMsg.getString("traceMessages");
            if (!(traceMsg.startsWith("[") && traceMsg.endsWith("]"))) {
                System.out.println(traceMsg);
                if (traceMsg.endsWith("\"")) {
                    dataBean.setFlag(true);
                    traceMsg = traceMsg.substring(0, traceMsg.length() - 1);
                }
                System.out.println(traceMsg);
            }
            defaultMsg.put("traceMessages", traceMsg);
            dataBean.setSource(jsonObject.toJSONString());
            return dataBean;
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage());
            exception.printStackTrace();
        }
        return dataBean;
    }

}
